package site.beanyon.now.aspect.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import site.beanyon.now.model.dto.TimeCardDTO;
import site.beanyon.now.service.UserService;

import java.util.List;
import java.util.Map;

/**
 * 时间数据分析日志切面
 */
@Aspect
@Component
class AnalysisLogAspect {
    private Logger logger = LoggerFactory.getLogger(AnalysisLogAspect.class);

    @Autowired
    private UserService userService;

    /**
     * 根据起止日志获取用户时间卡片分析数据日志切面
     *
     * @param jp 连接点
     * @return 获取结果
     */
    @Around("execution(* site.beanyon.now.service.AnalysisService.getAllData(String, String))")
    private List<TimeCardDTO> getAllData(ProceedingJoinPoint jp) throws Throwable {
        // 获取前
        Integer userId = this.userService.getCurrentUser().getId();
        String startDate = (String) jp.getArgs()[0];
        String endDate = (String) jp.getArgs()[1];

        List<TimeCardDTO> timeCardDTOList = null;

        try {
            timeCardDTOList = (List<TimeCardDTO>) jp.proceed();
        } catch (Throwable throwable) {
            // 获取异常
            logger.error("[error] get analysis data, user_id=" + userId
                    + ", start_date=" + startDate
                    + ", end_date=" + endDate);
            throw throwable;
        }

        // 获取后
        logger.info("[success] get analysis data, user_id=" + userId
                + ", start_date=" + startDate
                + ", end_date=" + endDate);

        return timeCardDTOList;
    }

    /**
     * 获取用户的所有时间卡片及对应的耗时数据，以及总耗时数据 日志切面
     *
     * @param jp 连接点
     * @return 数据Map
     */
    @Around("execution(* site.beanyon.now.service.AnalysisService.listAllActivity(..))")
    private Map<String, Object> listAllActivity(ProceedingJoinPoint jp) throws Throwable {
        // 获取前
        Integer userId = this.userService.getCurrentUser().getId();

        Map<String, Object> result = null;

        try {
            result = (Map<String, Object>) jp.proceed();
        } catch (Throwable throwable) {
            // 获取异常
            logger.error("[error] list all activity, user_id=" + userId);
            throw throwable;
        }

        // 获取后
        logger.info("[success] list all activity, user_id=" + userId);

        return result;
    }
}
